<?php
class WCore
{
    private static $ReturnCode;
    private static $ErrorCode;
    
    /**
    * Show a widget in template
    *
    * The fullpath of displayed widget start with name of the module that widget belong to
    * and use . as directory separator (Yii path format)
    *
    * @param mixed $path
    * @param mixed $params
    */
    public static function widget($path, $params = array(), $return = false)
	{
        //Inline param (params hardcoded into the page's template) which have the higest priority
        //$path = 'application.modules.'.str_replace('.','.components.',$path);

        preg_match('/application\.modules\.([a-zA-Z0-9_]*)\./',$path, $matches);
        if(!empty($matches))
        {
            $params['Module']= $matches[1];
        }

        // create the widget
        $widget = Yii::app()->controller->createWidget($path, $params);

        $html = $widget->run();

        if ($return == true)
            return $html;
        else
            echo $html;
    }
    
    /**
    * Execute a module service
    *
    * @param mixed $serviceId
    * @param mixed $data
    * @return ServiceResult
    */
    public static function service($serviceId, $data, $unwrap = null){
        $tmp = explode('.', $serviceId);
        if (count($tmp) != 3) throw new Exception("Invalid service ID format {$serviceId}. The correct service ID format is module/service/action");
        $class = ucfirst($tmp[1]).'Service';

        Yii::import($tmp[0].'.services.'.$class, true);
        if(!class_exists($class))
            throw new Exception("{$class} service is not found while trying to call service ID {$serviceId}");
        $service = new $class();

        if (!is_callable(array($service, $tmp[2])))
            throw new Exception("Function {$tmp[2]} is not found in {$class} service");

        $service->init($tmp[0]);
        
        $serviceResult = call_user_func(array($service, $tmp[2]), $data);
        //Assign the serviceID before returning
        $serviceResult->ServiceId = $serviceId;
        //Update CMS's latest service call status
        //self::$ReturnCode = $serviceResult->ReturnCode;
        //self::$ErrorCode = $serviceResult->ErrorCode;

        /**
        * Return service result
        * - if unwrap is set to TRUE, return only returned data, error code and return code
        * can be access via Cms::getServiceReturnCode() and Cms::getServiceErrorCode()
        * - if unwrap is set to a string, return only that part of the result
        */
        if (is_string($unwrap)) {
            return $serviceResult->ReturnedData[$unwrap];
        } elseif ($unwrap === TRUE) {
            return $serviceResult->ReturnedData;
        }
        return $serviceResult;
    }
}
?>
